<?php
/**
 * FTP file manipulator.
 *
 * @author Martin "DevelX" Jurča
 * @version 2009-09-14
 */
class FTP {
    private static $connection = null;

    public static function mkdir($path, $mode = 0777) {
        if (@mkdir(Config::ROOT . $path, $mode) === false) {
            self::connect();
            $result = @ftp_mkdir(self::$connection,
                    Config::FTP_DIRECTORY . $path);
            if ($result === false) {
                return false;
            }
            self::chmod($path, $mode);
        }
        return true;
    }

    public static function rmdir($path) {
        if (@rmdir(Config::ROOT . $path) === false) {
            self::connect();
            return @ftp_rmdir(self::$connection, Config::FTP_DIRECTORY . $path);
        }
        return true;
    }

    public static function createFile($path, $mode = 0666) {
        if (@touch(Config::ROOT . $path) === false) {
            self::connect();
            $result = @ftp_put(self::$connection, Config::FTP_DIRECTORY .
                    $path, Config::ROOT . '/index.php', FTP_ASCII,
                    @filesize(Config::ROOT . $path));
            if ($result === false) {
                return false;
            }
        }
        if (!self::chmod($path, $mode)) {
            return false;
        }
        $file = @fopen(Config::ROOT . $path, 'w');
        if (!is_resource($file)) {
            return false;
        }
        @fclose($file);
        return true;
    }

    public static function deleteFile($path) {
        if (!file_exists(Config::ROOT . $path) ||
                !is_file(Config::ROOT . $path)) {
            return false;
        }
        if (@unlink(Config::ROOT . $path) === false) {
            self::connect();
            return @ftp_delete(self::$connection,
                    Config::FTP_DIRECTORY . $path);
        }
        return true;
    }

    public static function chmod($path, $mode = 0777) {
        if (@chmod(Config::ROOT . $path, $mode) === false) {
            self::connect();
            $result = @ftp_chmod(self::$connection, $mode,
                    Config::FTP_DIRECTORY . $path);
            return $result !== false;
        }
        return true;
    }

    public static function close() {
        if (self::$connection != null) {
            @ftp_close(self::$connection);
        }
    }

    private static function connect() {
        if (self::$connection != null) {
            return;
        }
        self::$connection = @ftp_connect(Config::FTP_HOST);
        @ftp_login(self::$connection, Config::FTP_LOGIN, Config::FTP_PASSWORD);
    }
}
?>
